﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Logging;
using SyncService.Abstractions.Services;
using SyncService.Core.Model;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Threading.Tasks;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "ClearAssetMaster")]
    public class ClearAssetMasterService : SyncServiceBase
    {
        protected override string NotifyGroupName => "";
        private ILogger<ClearAssetMasterService> _logger = null;

        private bool IsNotPush = false;
        public ClearAssetMasterService() : base(YdConstants.YIDEA, "mysqlcache", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _logger = Resolver.Resolve<ILogger<ClearAssetMasterService>>();
        }
        public override void Execute(dynamic? state)
        {
            try
            {
                //清除自定义表单数据
                //UserDefine userDefine = UserDefines.First(x => x.Name == "资产主数据");
                //IEnumerable<CustomizedFormData> customizedFormDatas =YideaClient.GetCustomizedFormDatas(userDefine.Id, null);
                //int flag = 0;
                //List<string>data=new List<string>();
                //foreach (var item in customizedFormDatas) {
                //    flag++;
                //    data.Add(item.Id.ToString());
                //    if (flag == 100) {
                //        bool result= YideaClient.BatchDeleteCustomizedFormData(userDefine.Id, data.ToArray());
                //        flag = 0;
                //        data.Clear();
                //    }
                //}
                //if (flag > 0) {
                //    bool result = YideaClient.BatchDeleteCustomizedFormData(userDefine.Id, data.ToArray());
                //}
                //清除中间数据库数据
                var deleteResult = ToClient.DeleteAsset(new Asset());
                _logger.LogInformation("删除中间库数据：" + deleteResult);

                //拉取指定分类资产
                GetAssetMaster();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "定时任务发生异常");
            }

        }

        private void GetAssetMaster()
        {
            _logger.LogInformation("拉取资产开始");
            List<AssetType> assetTypeList = new List<AssetType>();
            List<string> typeCodes = new List<string>();
            List<string> topAssetType = new List<string>();
            List<string> assetTypeIds = new List<string>();
            List<Asset> assets = new List<Asset>();
            string assetCodeIds = string.Empty;
            try
            {
                assetTypeList = YideaClient.GetAssetTypes(null).ToList();
                var notPushAssetType = ExtendFields.Where(e => e.Name == "NotPushAssetType" && e.ObjectType == 0).First();
                typeCodes = notPushAssetType.FieldId.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();

                topAssetType = assetTypeList.Where(e => typeCodes.Contains(e.Code)).Select(e => e.Id.ToString()).ToList();
                assetTypeIds = assetTypeList.Where(e => topAssetType.Contains(e.Hierarchy.Split('|')[0])).Select(e => e.Code).ToList();

                assetCodeIds = string.Join(",", assetTypeIds.Select(q => q).ToArray());
                QueryParam queryParam = new QueryParam();
                queryParam.FilterObject = new JsonObject
                {
                    ["assetTypeCodeIn"] = assetCodeIds
                };
                queryParam.Take = 100;
                assets = YideaClient.GetAssets(queryParam).ToList();
                _logger.LogInformation(assets.Count + "条资产");
                ToClient.BatchAddAsset(assets);
                _logger.LogInformation("拉取资产结束");
            }
            catch (Exception ex)
            {

                _logger.LogInformation("GetAssetMaster" + ex.Message);
            }
            finally
            {
                //手动释放集合资源
                assetTypeList.Clear();
                typeCodes.Clear();
                topAssetType.Clear();
                assetTypeIds.Clear();
                assets.Clear();

                assetCodeIds = string.Empty;
            }
            


        }
    }
}
